#include "ZLogManager.h"
#include "../Common/ZException.h"
#include <cassert>

GLOBAL_NAMESPACE_BEGIN

template<> LogManager* Singleton<LogManager>::singleton_ = 0;
LogManager* LogManager::getSingletonPtr()
{
    return singleton_;
}

LogManager& LogManager::getSingleton()
{
    assert(singleton_);
    return *singleton_;
}

LogManager::LogManager()
    : pDefaultLog_(NULL)
{}

LogManager::~LogManager()
{
    destroy();
}

void LogManager::destroy()
{
    for (LogList::iterator it = logs_.begin(); it != logs_.end(); it++)
    {
        delete it->second;
    }
    logs_.clear();
    pDefaultLog_ = NULL;
}

Log* LogManager::createLog(const std::string& name, const std::string& fileName, bool defaultLog, bool debuggerOuput)
{
    Log* newLog = new Log(name, fileName, debuggerOuput);
    if (!pDefaultLog_ || defaultLog)
    {
        pDefaultLog_ = newLog;
    }
    logs_.insert(std::make_pair(name, newLog));
    return newLog;
}

Log* LogManager::getLog(const std::string& name)
{
    LogList::iterator iter = logs_.find(name);
    if (iter != logs_.end())
        return iter->second;
    else if (name.compare("Debug")==0)
        return pDefaultLog_;
    else
        ZFW_EXCEPTION(Exception::ERR_INVALID_PARAMS, "Log not found. ", "LogManager::getLog");
}

Log* LogManager::getDefaultLog()
{
    return pDefaultLog_;
}

void LogManager::destroyLog(const std::string& name)
{
    LogList::iterator iter = logs_.find(name);
    if (iter != logs_.end())
    {
        if (pDefaultLog_ == iter->second)
            pDefaultLog_ = 0;
        delete iter->second;
        logs_.erase(iter);
    }

    if (!pDefaultLog_ && !logs_.empty())
        pDefaultLog_ = logs_.begin()->second;
}

void LogManager::destroyLog(Log* log)
{
    destroyLog(log->getName());
}

Log* LogManager::setDefaultLog(Log* newLog)
{
    Log* oldLog = pDefaultLog_;
    pDefaultLog_ = newLog;
    return oldLog;
}

void LogManager::logMessage(const std::string& message, LogLevel level, bool maskDebug)
{
    if (pDefaultLog_)
        pDefaultLog_->logMessage(message, level, maskDebug);
}

Log::Stream LogManager::stream(LogLevel level, bool maskDebug)
{
    if (pDefaultLog_)
        return pDefaultLog_->stream(level, maskDebug);
    else
        ZFW_EXCEPTION(Exception::ERR_INVALID_PARAMS, "Default log not found. ", "LogManager::stream");
}

GLOBAL_NAMESPACE_END